package org.smile.db.meta.define;

import org.smile.db.JdbcSupports;
import org.smile.db.meta.TableMetaColumn;
import org.smile.util.StringUtils;

import java.sql.Types;
import java.util.List;

/**
 * mysql列的定义
 */
public class MySqlTableDefine extends AbstractTableDefine {

    @Override
    public String defineColumn(TableMetaColumn column) {
        //列名
        String name = "`"+column.getName()+"`";
        //类型
        Integer type = column.getType();
        if(type == null || type == 0){
            type= JdbcSupports.getJdbcType(column.getClassName());
        }
        String defineType = defineType(type,column.getLength());

        StringBuilder sql= new StringBuilder(name + defineType );
        if(column.isNotNull()){
            sql.append(" not null " );
        }
        if(column.getDefaultValue()!=null){
            if(column.getDefaultValue() instanceof String){
                sql.append(" default '").append(column.getDefaultValue()).append("' ");
            }
        }
        if(StringUtils.notEmpty(column.getRemark())){
            sql.append(" comment ").append("'").append(column.getRemark()).append("'");
        }
        return sql.toString();
    }

    @Override
    public String defineTable(String tableName, List<TableMetaColumn> columns,List<String> keys) {
       StringBuilder defineSql = new StringBuilder();
       defineSql.append("create table ").append("`").append(tableName).append("`(");
       int size = 0;
       for(TableMetaColumn column:columns){
           defineSql.append(defineColumn(column));
           if(size<columns.size()-1){
                defineSql.append(",");
           }
           size++;
       }
        if(keys.size()>0){
            defineSql.append(",").append("PRIMARY KEY (").append(StringUtils.join(keys,","));
        }
        defineSql.append(")");
        return defineSql.toString();
    }

    private String defineType(Integer jdbcType,int length){
        switch (jdbcType){
            case Types.VARCHAR:
                if(length<Short.MAX_VALUE){
                    return "varchar("+length+")";
                }else{
                    return "text";
                }
            case Types.LONGVARCHAR:
                return "text";
            case Types.TIMESTAMP_WITH_TIMEZONE:
                return "datetime";
            case Types.BOOLEAN:
                return "bit";
            case Types.CHAR:
                return "char("+length+")";
            default:
                return JdbcSupports.getJdbcTypeName(jdbcType);
        }
    }
}
